package view.lcdui.menu;

import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

/**
 * Composite pattern to create a cascading menu.
 * The children of the Menu can be other Menu or any other
 * class that extend the Component class to do specialized action.
 * 
 * Based on the article "Big designs for small devices"
 * 
 * @author Marcelo Gatto
 */
public class Menu extends List implements CommandListener, Component {
	
	public final static Command BACK_COMMAND  = new Command("Back",  Command.SCREEN, 1);
	
	public static Display display = null;

	private Menu prevMenu = null;
	private Vector child = new Vector();
	
	public Menu(String title) {
		super(title, List.IMPLICIT);
		setCommandListener(this);
	}
	
	/**
	 * Add a child component 
	 */
	public void addChild(String title, Component c) {
		child.addElement(c);
		append(title, null);
	}
	
	/**
	 * Set the previous Menu for the 'back' command
	 */
	private void setPreviousMenu(Menu m) {
		prevMenu = m;
	}
	
	public void commandAction(Command command, Displayable displayable) {
		if(command==BACK_COMMAND) {
			display.setCurrent(prevMenu);
			return;
		}
		
		Component next = (Component)child.elementAt(getSelectedIndex());
		if(next instanceof Menu) {
			((Menu)next).setPreviousMenu(this);
			((Menu)next).addCommand(BACK_COMMAND);
		}
		next.action();
	}

	/**
	 * Default action method of a Menu is display it
	 */
	public void action() {
		display.setCurrent(this);
	}
	
}